library(scales)
library(dplyr)
library(tidyr)
library(ggplot2)
library(showtext)

# Register the Nunito Sans font from Google Fonts
font_add_google("Nunito Sans", "Nunito Sans")
showtext_auto()
# Country list
c_list <- c(
  "Argentina", "Botswana", "Brazil", "Cote d'Ivoire", "Gabon",
  "Ghana", "Kenya", "Senegal", "Uganda", "Zambia"
)

# Prepare the data
data_cut <- data %>%
  filter(year %in% c(2021, 2024)) %>%
  filter(group == "all") %>%
  mutate(
    ts_savother = ts_anysavings - ifelse(is.na(ts_savfor_mm), 0, ts_savfor_mm) - ts_savfor_fi_MErank - ts_savsemfor_MErank,
    saved_fi_only = ts_savfor_fi_MErank,
    saved_mm_only = ts_savfor_mm_MErank,
    saved_both = (ts_savfor_mm + ts_savfor_fi - ts_savfor_fi_mm),
    saved_semiformal = ts_savsemfor_MErank,
    saved_other = ts_savother
  )

plot_sav <- data_cut %>%
  filter(countrynewwb %in% c_list) %>%
  select(countrynewwb, year, saved_fi_only, saved_mm_only, saved_both, saved_semiformal, saved_other, ts_anysavings) %>%
  pivot_longer(cols = c(saved_fi_only, saved_mm_only, saved_both, saved_semiformal, saved_other), names_to = "group", values_to = "value") %>%
  mutate(
    total = ts_anysavings * 100,
    value = value * 100
  ) %>%
  filter(!is.na(value))

plot_sav$year <- factor(plot_sav$year, levels = c(2021, 2024))

# Determine plot dimensions
length_unique_countries <- n_distinct(plot_sav$countrynewwb)
width_num <- ifelse(length_unique_countries < 8, 8, 8 + floor((length_unique_countries - 1) / 4) * 2)
height_num <- ifelse(length_unique_countries < 8, 4, 4 + floor((length_unique_countries - 1) / 4))

# Create the plot with flipped axes and horizontal bars
# Create the plot with flipped axes and horizontal bars
p <- ggplot(plot_sav) +
  geom_bar(aes(
    y = factor(year, levels = c(2024, 2021)),  # Ensuring 2021 appears first
    x = value,
    fill = factor(group, levels = c(
      "saved_other", "saved_semiformal", "saved_mm_only", "saved_both", "saved_fi_only"
    ))
  ),
  stat = "identity",
  position = "stack",
  width = 0.75,
  color = "black",
  size = 0.75
  ) +
  scale_fill_manual(
    values = c(
      "saved_other" = "#E6E6E6",
      "saved_semiformal" = "#878787",
      "saved_mm_only" = "#D12891",
      "saved_both" = "#8066AB",
      "saved_fi_only" = "#5696D0"
    ),
    breaks = c(
      "saved_fi_only",
      "saved_both",
      "saved_mm_only",
      "saved_semiformal",
      "saved_other"
    ),
    labels = c(
      "Saved formally at a bank or similar financial institution only",
      "Saved formally at a bank or similar financial institution and using a mobile money account",
      "Saved formally using a mobile money account only",
      "Saved semiformally",
      "Saved using other methods only"
    )
  ) +
  scale_x_continuous(
    limits = c(0, 150),
    breaks = seq(0, 100, by = 20)
  ) +
  facet_grid(countrynewwb ~ ., 
             scales = "free", 
             space = "free", 
             switch = "both", 
             labeller = label_wrap_gen(width = 9, multi_line = TRUE)) +
  theme(
    strip.placement = "outside",
    strip.text.y.left = element_text(size = 28, family = "Nunito Sans", colour = "black", angle = 0),  # Set angle to 0 like the years
    panel.background = element_blank(),
    strip.background = element_blank(),
    panel.grid.major.y = element_blank(),
    panel.grid.minor.y = element_blank(),
    panel.grid.major.x = element_blank(),
    panel.grid.minor.x = element_blank(),
    panel.border = element_blank(),
    legend.title = element_blank(),
    legend.position = "bottom",
    legend.justification = "center",
    legend.box.margin = margin(0, 0, 20, 0),
    axis.text.y = element_text(size = 24, family = "Nunito Sans", color = "black", margin = margin(r = 5)),
    axis.text.x = element_text(size = 22, family = "Nunito Sans", color = "black"),
    axis.ticks.y = element_blank(),
    axis.ticks.x = element_line(color = "black"),
    axis.title.y = element_blank(),
    axis.title.x = element_blank(),
    plot.subtitle = element_text(size = 32, color = "black", family = "Nunito Sans"),
    plot.title = element_text(
      hjust = 0,
      size = 34,
      color = "black",
      family = "Nunito Sans",
      face = "bold"
    ),
    plot.title.position = "plot",
    legend.text = element_text(
      hjust = 0,
      size = 28,
      color = "black",
      family = "Nunito Sans"
    ),
    legend.text.align = 0,
    plot.caption = element_text(size = 28, family = "Nunito Sans", hjust = 0),
    plot.caption.position = "plot",
    plot.margin = margin(t = 10, r = 10, b = 40, l = 10),
    size = 12,
    family = "Nunito Sans",
    color = "black"
  ) +
  guides(fill = guide_legend(ncol = 1)) +
  labs(
    subtitle = "Adults saving any money in the past year (%), 2021-2024",
    title = "In the top 10 economies with the highest share of adults saving using mobile money accounts, mobile money is increasing the share\nof adults who save formally",
    caption = "\n\nSource: Global Findex Database 2025\n\nNote: People may save in multiple ways, but categories in the figure are constructed to be mutually exclusive. 'Saved formally' includes all adults who saved any\nmoney formally. 'Saved semiformally' includes all adults who saved money semiformally but not formally."
  )

# Show the plot
p

# Save the plot
ggsave(
  filename = file.path(folder_path, "3.1.5.png"),
  plot = p,
  width = 23,
  height = 20,
  units = "in",
  device = 'png',
  dpi = 120
)



